public class Solution1008 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode bstFromPreorder(int[] preorder) {
        return dfs(preorder,0,preorder.length-1);
    }

    private TreeNode dfs(int[] preorder, int start, int end) {
        if (start>end){
            return null;
        }
        TreeNode treeNode=new TreeNode(preorder[start]);
        int t=start+1;
        while (t<=end && preorder[t]<preorder[start]){
            t++;
        }
        treeNode.left=dfs(preorder,start+1,t-1);
        treeNode.right=dfs(preorder,t,end);
        return treeNode;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1008().bstFromPreorder(new int[]{8,5,1,7,10,12}).left.right.val);
    }
}
